package com.example.mvicore.model

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import com.example.mvicore.IIntent
import com.example.mvicore.IModel
import com.example.mvicore.IState
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

abstract class BaseModel<I:IIntent,S:IState> constructor(lifecycleOwner: LifecycleOwner)
    :IModel<I,S> ,ViewModel(),DefaultLifecycleObserver{
    init {
        //监听生命周期
        lifecycleOwner.lifecycle.addObserver(this)
    }

    //对内和对外使用的意图
    protected var _events:Channel<I> = Channel()
    override val events:Channel<I>
        get() = _events

    //对内使用和对外使用的状态
    protected var _status:MutableStateFlow<S> = MutableStateFlow<S>(generateInitState())
    override val status:StateFlow<S>
        get() = _status

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        //意图传递
        handleIntent()
    }

    //热流初始化需要传参
    abstract fun generateInitState() :S
}